# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import DatabaseError, connection
from django.db import models
from django.db.models.signals import post_save
from wenlincms.conf import settings
from wenlincms.core.fields import FileField
from wenlincms.utils.models import lazy_model_ops
from wenlincms.utils.models import upload_to

from wlapps.accounts import get_profile_for_user

__all__ = ()

if getattr(settings, "AUTH_PROFILE_MODULE", None):

    # This will be called when class_prepared signal has been sent
    # for both the profile and user model.
    def wait_for_models(profile_model, user_model):

        def create_profile(sender, instance, created, **_):
            if created:
                try:
                    get_profile_for_user(instance)
                except DatabaseError:
                    # User creation in initial syncdb may have been triggered,
                    # while profile model is under migration management and
                    # doesn't exist yet. We close the connection so that it
                    # gets re-opened, allowing syncdb to continue and complete.
                    connection.close()

        post_save.connect(create_profile, sender=user_model, weak=False)


    lazy_model_ops.add(wait_for_models, settings.AUTH_PROFILE_MODULE, settings.AUTH_USER_MODEL)


# 用户信息
class WLUserProfile(models.Model):
    user = models.OneToOneField("auth.User")
    nickname = models.CharField(max_length=50, blank=True, verbose_name='昵称')
    telephone = models.CharField(max_length=20, blank=True, verbose_name='移动电话')
    avatar = FileField(verbose_name="用户头像",
                       upload_to=upload_to("accounts.WLUserProfile.avatar", "wluserprofile/avatar"),
                       format="Image", null=True, blank=True)

    class Meta:
        verbose_name = '用户信息'
        verbose_name_plural = '用户信息'
        db_table = 'auth_user_userprofile'
